<template>
    <div class="data-gather-list-wrap">
        <div class="search-table-tool">
            <div class="s-row">
                <div class="input-wrap">
                    <span class="label">{{ $t('XX查询条件') }}:</span>
                    <ElInput v-model="searchForm.vin" popper-class="popper-style" :teleported="false" placement="top">
                    </ElInput>
                </div>
                <div class="input-wrap">
                    <span class="label">{{ $t('XX信息查询') }}:</span>
                    <ElInput v-model="searchForm.partInformation" popper-class="popper-style" :teleported="false"
                        placement="top">
                    </ElInput>
                </div>
                <ElButton round plain @click="Search">
                    {{ $t('搜索') }}
                </ElButton>
            </div>
            <div class="s-row">
                <div class="input-wrap">
                    <span class="label">{{ $t('报警类型') }}:</span>
                    <ElSelect v-model="searchForm.reason_code" popper-class="popper-style" :teleported="false"
                        placement="top" :placeholder="$t('Select')">
                        <el-option v-for="(option, i) in searchFormReasonOptions" :key="i"
                            :label="getTranslatedText(option.label)" :value="option.value" />
                    </ElSelect>
                </div>
                <el-config-provider :locale="i18n_local">
                    <el-date-picker v-model="pickerDate" class="data-gather-picker-date" type="datetimerange"
                        style="flex: 1;" :start-placeholder="$t('Start Date')" :end-placeholder="$t('End Date')"
                        :default-time="defaultTime1" :prefix-icon="customPrefix" @change="handleChangeTime" />
                </el-config-provider>
                <ElButton round type="primary" @click="resetSearch">
                    {{ $t('Reset') }}
                </ElButton>
            </div>
        </div>
        <div class="table-visual-frame borders-are-thick">
            <GeneralTable :cols="colsMax" :data="tableData" :isShowPagination="true" :isShowSelection="false"
                :is-show-index="false" :pageConfig="{
                    layout: 'prev, pager, next, jumper, slot',
                    total: totalVideo,
                    background: true,
                    small: true,
                    pageSize: pageSize
                }" v-bind="$attrs" @getCurrentPage="handleSizeChange" @selection-change="handleSelectionChange">

                <template #[`state`]="{ row }">
                    <SvgIcon :icon-class="row.state === false ? 'error' : 'right'" style="vertical-align: middle" />
                </template>
                <template #filename>
                    <svg-icon :icon-class="searchForm.sort['filename'] === -1 ? -1 : 1"
                        @click="sortTable('filename')" />
                </template>
                <template #start_end_head>
                    <svg-icon :icon-class="searchForm.sort['video_start'] === -1 ? -1 : 1"
                        @click="sortTable('video_start')" />
                </template>
                <template #video_start>
                    <svg-icon :icon-class="searchForm.sort['video_start'] === -1 ? -1 : 1"
                        @click="sortTable('video_start')" />
                </template>
                <template #video_end>
                    <svg-icon :icon-class="searchForm.sort['video_end'] === -1 ? -1 : 1"
                        @click="sortTable('video_end')" />
                </template>
                <template #video_start_format="{ row }">
                    <div>
                        <ElTooltip popper-class="td-time-tooltip">
                            <template #content>
                                <span>{{ row.video_start_format }}</span>
                            </template>
                            <span class="td-time-tooltip-title">
                                {{ row.video_start_format }}
                            </span>
                        </ElTooltip>
                    </div>
                </template>
                <template #video_end_format="{ row }">
                    <div>
                        <ElTooltip popper-class="td-time-tooltip">
                            <template #content>
                                <span>{{ row.video_end_format }}</span>
                            </template>
                            <span class="td-time-tooltip-title">
                                {{ row.video_end_format }}
                            </span>
                        </ElTooltip>
                    </div>
                </template>
                <template #doing="{ row }">
                    <div class="cell-btns">
                        <el-tooltip effect="dark" :content="$t('Preview')">
                            <svg-icon className="table-td-play" icon-class="play" @click="getRowData(row)" />
                        </el-tooltip>
                    </div>
                </template>
            </GeneralTable>
        </div>
    </div>
</template>

<script lang="ts" setup>

import router from '@/vue-router'

import { zhCn, en } from 'element-plus/es/locale/index.mjs'
import {
    getTimeComponentStrings,
    formatTimestamp,
} from '@/utils'
import {
    T_Camera_Video_Row,
    T_Warn_List_Row,
    T_Camera_Video_List_Request_Condition
} from './types'

import {
    confirmedCamera,
    xmeDSIC_Solutions_History,
} from '@/data-services/api'
import { i18n } from '@/vue-i18n'
import {
    useStore_ViewportsGrid_Detail,
} from '@/pages/pinia'
const vsp_ViewportsGrid = useStore_ViewportsGrid_Detail()

import { userConfig } from '@/pages/pinia/user/index'
const userConfigStore = userConfig()


interface T_Props {
    cameraIp?: string;
}

interface T_Time_Result {
    year?: string;
    month?: string;
    day?: string;
    hour?: string;
    minute?: string;
    second?: string;
}

const props = defineProps<T_Props>()

const $emit = defineEmits([
    'getVideoRow',
    'handleRepositionClick',
])

const $t = i18n.global.t
const totalVideo = ref(0)
const pageSize = ref(5)

const tableData = ref<T_Warn_List_Row[]>([])
const selCameraVideoVal = ref<T_Camera_Video_Row[]>([])

const pickerDate = ref('')
const defaultTime1 = new Date()
const searchForm = reactive<T_Camera_Video_List_Request_Condition>({
    vin: '',
    partInformation: '',
    addr: props.cameraIp || '',
    type: 1,
    reason_code: '',
    dateRange: {
        start: 0,
        end: 0,
    },
    sort: {
        video_start: -1,
    },
})

const pageConfigCameraVideo = reactive({
    pageSize: 5,
    pageNumber: 1,
    totalRecords: 0,
})

function goHome() {
    setTimeout(() => {
        router.replace({
            name: 'Index',
        })
        vsp_ViewportsGrid.clearOnPreviewingCamera()
    }, 2000)

}

function getTranslatedText(text: string) {
    if (!text) return
    return $t(text)
}

function handleSizeChange(currentPage: number, everyPageNumber: number) {
    pageConfigCameraVideo.pageSize = everyPageNumber
    pageConfigCameraVideo.pageNumber = currentPage + 1
    searchFun(currentPage + 1)
}

const handleChangeTime = () => {
    if (!pickerDate.value || !pickerDate.value.length) {
        searchForm.dateRange && (searchForm.dateRange.start = 0)
        searchForm.dateRange && (searchForm.dateRange.end = 0)
        return
    }
    const startTime = new Date(pickerDate.value[0])
    const endTime = new Date(pickerDate.value[1])

    searchForm.dateRange && (searchForm.dateRange.start = startTime.getTime())
    searchForm.dateRange && (searchForm.dateRange.end = endTime.getTime())
}
// 方法
const Search = () => {
    const searchFormData = {
        vin: searchForm.vin,
        partInformation: searchForm.partInformation,
        startTime: searchForm.dateRange.start ? formatTimestamp(searchForm.dateRange.start) : '',
        endTime: searchForm.dateRange.end ? formatTimestamp(searchForm.dateRange.end) : '',
        state: searchForm.reason_code,
    };

    // 调用接口
    xmeDSIC_Solutions_History(searchFormData, pageConfigCameraVideo.pageSize, pageConfigCameraVideo.pageNumber)
        .then(response => {
            if (response.rows) {
                tableData.value = response.rows
                totalVideo.value = response.total
            }
        })
        .catch(error => {
            console.error('搜索失败：', error);
        });
};

const getVideoList = async (paginationPageIndex?: number, seachData?: any) => {
    const params = {
        vin: searchForm.vin,
        partInformation: searchForm.partInformation,
        startTime: searchForm.dateRange.start ? formatTimestamp(searchForm.dateRange.start) : '',
        endTime: searchForm.dateRange.end ? formatTimestamp(searchForm.dateRange.end) : '',
        state: searchForm.reason_code,
    }

    try {
        const res = await xmeDSIC_Solutions_History(params, pageConfigCameraVideo.pageSize, pageConfigCameraVideo.pageNumber)
        if (res) {
            tableData.value = res.rows
            totalVideo.value = res.total

            tableData.value.map(item => {
                let start: T_Time_Result = {}
                let end: T_Time_Result = {}
                if (typeof item.videoStart === 'number') {
                    start = getTimeComponentStrings(item.videoStart)
                    item.video_start_format = `${start.year}.${start.month}.${start.day} ${start.hour}:${start.minute}:${start.second}`
                }
                if (typeof item.video_end === 'number') {
                    end = getTimeComponentStrings(item.video_end)
                    item.video_end_format = `${end.year}.${end.month}.${end.day} ${end.hour}:${end.minute}:${end.second}`
                    item.video_time_view = item.video_start && Math.ceil((item.video_end - item.video_start) / 1000)
                }
                if (!item.video_start && item.timestamp && typeof item.timestamp === 'number') {
                    start = getTimeComponentStrings(item.timestamp)
                    item.video_start_format = `${start.year}.${start.month}.${start.day} ${start.hour}:${start.minute}:${start.second}`
                }
            })
        }
    } catch (error) {
        console.log(error)
    }
}


//视频播放
function getRowData(row: T_Camera_Video_Row): void {
    $emit('getVideoRow', row)
}
const handleSelectionChange = (selVal: T_Camera_Video_Row[]) => {
    selCameraVideoVal.value = selVal
}

async function submitConfirmed(): Promise<boolean | Array<string>> {
    const confirmedList = selCameraVideoVal.value.filter(item => !item.confirmed)
    if (!confirmedList.length) {
        ElMessage({
            type: 'warning',
            message: $t('暂无告警确认条目'),
            duration: 2000,
        })
        return false
    }
    let ids = confirmedList.map(item => {
        if (!item.confirmed && item._id) {
            return item._id
        }
    }) as Array<string>

    ids = ids.filter(item => item)

    if (ids && ids.length) {
        try {
            await confirmedCamera({ records: ids })
            ElMessage({
                type: 'success',
                message: $t('Successfully'),
                duration: 2000,
            })
            await searchFun()
            if (!tableData.value.length) {
                goHome()
            }
        } catch (error: any) {
            ElMessage({
                type: 'error',
                message: error.message || $t('error'),
            })
        }
    }
    return false
}

const resetSearch = () => {
    tableData.value = ''
    pickerDate.value = ''
    searchForm.vin = ''
    searchForm.partInformation = ''
    searchForm.confirmed = ''
    searchForm.reset = ''
    searchForm.type = 1
    searchForm.dateRange && (searchForm.dateRange.start = 0)
    searchForm.dateRange && (searchForm.dateRange.end = 0)
}


// $t('事件时间:')
const customPrefix = shallowRef({
    render() {
        return h('p', { class: 'label' }, $t('事件时间:'))
    },
})

const searchFormReasonOptions = ref<{
    label: any;
    value: number | '';
}[]>([
    {
        label: '正常事件', // $t('分析')
        value: 1,
    },
    {
        label: '异常事件', // $t('物料分析检测')
        value: 0,
    }
])

const searchFun = async (pageNum?: number) => {
    const paramsWarn = {
        filename: "",
        sort: { "video_start": -1 },
        type: searchForm.type === '-1' ? '' : searchForm.type,
    }

    if (searchForm?.dateRange && (searchForm.dateRange.start !== 0 || searchForm.dateRange.end !== 0)) {
        paramsWarn.dateRange = {
            start: searchForm.dateRange.start,
            end: searchForm.dateRange.end,
        };
    }

    return getVideoList(pageNum || 1, paramsWarn)
}



defineExpose({ getVideoList, searchFun, submitConfirmed })

let colsMax = [
    {
        label: 'End_time',
        prop: 'eTime',
        width: '220px',
        headSlot: false,
        slot: false,
        showOverflowTooltip: false,
    },
    {
        label: 'vin',
        prop: 'vin',
        width: 'fit-content',
        headSlot: false,
        slot: false,
        showOverflowTooltip: true,
    },
    {
        label: 'ipNumbering',
        prop: 'cameraId',
        width: 'fit-content',
        headSlot: false,
        slot: false,
        showOverflowTooltip: true,
    },
    {
        label: 'actionStatus2',
        prop: 'state',
        width: '80px',
        headSlot: false,
        slot: true,
        showOverflowTooltip: false,
    },

]
// $t('Controls')  $t('Start time')  $t('Reason') 

const permission = computed(() => userConfigStore.permission)

watch(permission, (val) => {
    if (val == 0) {
        const columnBtn = [
            {
                label: 'Controls',
                propHead: '',
                prop: 'doing',
                width: '120px',
                slot: true,
                headSlot: false,
                fixed: 'right',
                showOverflowTooltip: false,
            },
        ]
        colsMax = [...colsMax, ...columnBtn]
    }
}, { immediate: true })

let i18n_local = zhCn

watch(() => i18n.global.locale, (local: any) => {
    if (local.value === 'zh-Hans') {
        i18n_local = zhCn
    }
    if (local.value === 'en') {
        i18n_local = en
    }
}, { immediate: true, deep: true })
</script>
<style lang="scss" scoped>
@use 'sass:map';

.table-tool-btn {
    display: flex;
    justify-content: end;
    margin-top: -12px;
    margin-bottom: 8px;
}

.data-gather-list-wrap {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    flex: 1;

    .table-visual-frame {
        display: flex;
        flex-direction: column;
        overflow: auto;
        height: 100%;

        .el-icon {
            font-size: 18px;
            color: #2E7FAC;
        }
    }

    .table-bottomb-btn-wrap {
        flex: 0;
        margin-top: 10px;
    }
}
</style>
<style lang="scss">
$checkedColor: #7688C9;
$grayTextColorTip: #B5B5BE;

.el-popper.is-dark {
    font-size: 15px;
    color: $grayTextColorTip;
}

.td-time-tooltip-title {
    display: flex;
    align-items: center;
    padding-left: 12px;
    font-size: 20px !important;
    cursor: pointer;
}

.search-table-tool {
    display: flex;
    flex: 0;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    box-sizing: border-box;
    margin-bottom: 10px;
    border-radius: 8px;

    .s-row {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        gap: 10px;

        .el-date-editor .el-range__icon {
            white-space: nowrap;
            padding: 0 25px;
        }

        .el-date-editor .el-range-separator {
            font-size: 20px;
            color: var(--el-text-color-regular);
        }

        .label {
            font-size: 14px;
            color: var(--el-text-color-regular);
        }
    }

    /* 搜索按钮样式 */
    .el-button {
        display: flex;
        align-items: center;
        padding: 0;
        gap: 8px;
        width: 120px;
        height: 36px;
        background-color: rgb(50, 50, 50);
        color: #36B5AC;
        border: 1px solid #36B5AC;
        border-radius: 10px;
    }

    .el-link {
        font-size: 20px;
        color: #fff;
        font-weight: bold;

        &:hover {
            color: #fff5;
        }

        &:active {
            color: #46B0DD;
        }
    }

    .input-wrap {
        display: flex;
        align-items: center;
        flex: 1;

        .label {
            white-space: nowrap;
            margin-right: 0;
            color: #36B5AC;
        }
    }
}

.el-table .cell {
    font-size: 16px;
}

.data-gather-list-wrap {
    .cell-btns {
        display: flex;
        align-items: center;
        gap: 14px;

        .table-td-download,
        .cell-del {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 22px;
            height: 22px;
            flex-shrink: 0;
            border-radius: 6px;
            background-color: var(--color-primary);

            .svg-icon {
                width: 16px;
                height: 16px;
            }
        }

        .cell-del {
            background-color: transparent;
            border: solid 1px rgba(252, 90, 90, 1);

            .svg-icon {
                width: 16px;
                height: 16px;
            }
        }

        .table-td-play {
            width: 22px;
            height: 22px;
        }

        .svg-icon {
            color: #46B0DD;
        }

        &:last-child {
            // justify-content: center;
            margin-top: 10px;
        }
    }

    .cell {
        .svg-icon {
            cursor: pointer;
        }
    }

    .record-code {
        width: 160px;
        height: 1.5rem;
        margin-top: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding: 2px 10px;
        font-size: 16px;
        color: #fff;
        border-radius: 4px;
        border: 1px solid #5571D4;
        background: var(--primary-opacity-4, rgba(56, 85, 179, 0.04));
    }
}

.code-error-popper.el-popover.el-popper.top-user-popper {
    width: 100%;
    min-width: 350px;

    h4 {
        display: flex;
        gap: 10px;
        color: #FAFAFB;
        font-size: 20px;
        font-style: normal;
        font-weight: 800;
        line-height: normal;
        letter-spacing: 0.1px;
    }

    .code-warning {
        animation: none;
        width: 30px;
        height: 30px;
    }

    .el-radio.is-bordered {
        flex-shrink: 0;
        width: 100%;
        height: auto;
        margin-top: 10px;
        color: #fff;
        padding: 6px 19px 6px 11px;
        border-color: $checkedColor;

        &.el-radio--large {
            .el-radio__label {
                p {
                    font-size: 18px;
                }
            }
        }
    }

    .btn-wrap {
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
    }
}

.record-code-wrap {
    position: relative;
    display: flex;
    align-items: center;
    padding-left: 12px;

    .code-warning {
        position: absolute;
        left: -12px;
        animation: none;
        width: 18px;
        height: 18px;
    }
}
</style>
